<template>
  <view>
    <basics-form
      ref="basicsForm"
      @submit="submit"
      @selectCallback="selectCallback"
    />
    <foot-button
      :buttonList="buttonList"
      v-if="!order"
      @tapButton="tapButton"
    />

    <foot-button
      v-if="spFlag"
      :buttonList="buttonList2"
      @tapButton="tapButton2"
    />
    <view style="height: 200rpx" />
  </view>
</template>

<script>
import basicsForm from "@/components/basics-form/basics-form.vue";
import footButton from "@/components/foot-button/foot-button.vue";

export default {
  components: {
    basicsForm,
    footButton,
  },
  data() {
    return {
      pzhAuthorization: uni.getStorageSync("pzhAuthorization"),
      loginAccount: uni.getStorageSync("loginAccount"),
      spFlag: false,
      order: null,
      ycr: 0,
      jsy: 0,
      pcr: 0,
      xfsprArr: [],
      car: [],
      buttonList: [
        { name: "重置", icon: "zhongzhi-" },
        { name: "保存", icon: "save" },
      ],
      buttonList2: [{ name: "审批", icon: "save" }],
    };
  },
  onLoad(options) {
    if (options.id) {
      this.getData(options.id);
      if (options.spFlag) {
        uni.setNavigationBarTitle({ title: "审批派车单" });
        this.spFlag = true;
      } else {
        uni.setNavigationBarTitle({ title: "派车单详情" });
      }
    } else {
      this.getConfig();
    }
  },
  methods: {
    getData(id) {
      this.$api
        .selectClglPcgl({
          id,
          pzhAuthorization: this.pzhAuthorization,
          flag: "info",
          deleteflag: 0,
        })
        .then((res) => {
          if (res.resCode == "success") {
            let item = res.datas[0];
            item.file = [];
            if (item.attachList) {
              item.attachList = item.attachList.replace(
                /127.0.0.1/g,
                `192.168.0.8`
              );
              let re = /<a.*?>/g;
              let re1 = /<img.*?>/g;
              let arr = item.attachList.match(re);
              let arr1 = item.attachList.match(re1);
              if (arr != undefined && arr.length) {
                arr.forEach((it) => {
                  item.file.push(
                    it.match(/\shref=['"](.*?)['"]/)[1] +
                      `&pzhAuthorization=${this.pzhAuthorization}`
                  );
                });
              }
              if (arr1 != undefined && arr1.length) {
                arr1.forEach((it) => {
                  item.file.push(
                    it.match(/\ssrc=['"](.*?)['"]/)[1] +
                      `&pzhAuthorization=${this.pzhAuthorization}`
                  );
                });
              }
              item.attachList = "";
            }
            this.order = item;
            this.getConfig();
          }
        });
    },
    getConfig() {
      this.$api
        .selectUserOptionsList({
          pzhAuthorization: this.pzhAuthorization,
          params: `[{"executionClass":"default"},{"needNull":false,"executionClass":"cn.scihi.zhgl.ucc.HtUcc","roleIds":"1139412245311086594,1141270155063418881"}]`,
        })
        .then((res) => {
          uni.hideLoading();
          if (res.resCode == "success") {
            let user = [];
            let audit = res.datas["cn.scihi.zhgl.ucc.HtUcc"].map(
              (item, index) => {
                item.name = item.NAME + `(${item.ACCOUNT})`;
                if (
                  this.order &&
                  this.order.xfsprArr.indexOf(item.ACCOUNT) > -1
                ) {
                  this.xfsprArr.push(index);
                }
                return item;
              }
            );
            if (this.order) {
              user = res.datas.default.map((item, index) => {
                item.name = item.NAME + `(${item.ACCOUNT})`;
                if (item.ACCOUNT == this.order.ycr) {
                  this.ycr = index;
                }
                if (item.ACCOUNT == this.order.jsy) {
                  this.jsy = index;
                }
                if (item.ACCOUNT == this.order.pcr) {
                  this.pcr = index;
                }
                return item;
              });
              this.initRules(audit, user, this.car, this.order);
              return;
            }
            this.$api
              .selectClgl({
                pzhAuthorization: this.pzhAuthorization,
                status: 1,
              })
              .then((res1) => {
                uni.hideLoading();
                if (res1.resCode == "success") {
                  if (!res1.datas.length) {
                    uni.showToast({
                      icon: "none",
                      title: "暂无可用车辆",
                      duration: 2000,
                    });
                    setTimeout(() => {
                      this.$util.goUrl(0);
                    }, 1500);
                    return;
                  }
                  user = res.datas.default.map((item, index) => {
                    item.name = item.NAME + `(${item.ACCOUNT})`;
                    if (item.ACCOUNT == this.loginAccount) {
                      this.ycr = index;
                    }
                    if (item.ACCOUNT == res1.datas[0].clgl_jsy) {
                      this.jsy = index;
                    }
                    return item;
                  });

                  this.car = res1.datas;
                  this.initRules(audit, user, this.car, this.order);
                }
              });
          }
        });
    },
    tapButton(index) {
      if (index) {
        this.$refs.basicsForm.formValid();
      } else {
        this.$refs.basicsForm.formReset();
      }
    },
    tapButton2() {
      uni.showModal({
        title: "意见",
        placeholderText: "请输入审批意见",
        editable: true,
        success: (res) => {
          if (res.confirm) {
            console.log({
              yj: res.content,
              xfsprList: JSON.stringify(this.order.xfsprList),
              result: "提交",
              id: this.order.id,
              status: this.order.status,
              pzhAuthorization: this.pzhAuthorization,
            });
            this.$api
              .updateClglPcgl({
                yj: res.content,
                result: "提交",
                id: this.order.id,
                status: this.order.status,
                pzhAuthorization: this.pzhAuthorization,
              })
              .then((res1) => {
                console.log(res1, "===");
                if (res1.resCode == "success") {
                  uni.hideLoading();
                  uni.showToast({
                    icon: "success",
                    title: "操作成功",
                    duration: 2000,
                  });
                  setTimeout(() => {
                    this.$util.backToRefreshPrevPage("carOrder");
                  }, 1500);
                }
              });
          }
        },
      });
    },
    initRules(audit, user, car, order) {
      let carValue = 0;
      if (order) {
        carValue = order.cph;
      }
      let disabled = order ? true : false;
      let rules = [
        {
          title: "用车人",
          key: "ycr",
          type: "select",
          selectList: user,
          selectKey: "ACCOUNT",
          value: this.ycr,
          disabled,
        },
        {
          title: "车牌号",
          key: "cph",
          type: order ? "" : "select",
          selectList: car,
          selectShowKey: "clgl_cph",
          value: carValue,
          disabled,
        },
        {
          title: "驾驶员",
          key: "jsy",
          type: "select",
          selectList: user,
          selectKey: "ACCOUNT",
          value: this.jsy,
          disabled,
        },
        {
          title: "派车人",
          key: "pcr",
          type: "select",
          selectList: user,
          selectKey: "ACCOUNT",
          value: this.pcr,
          disabled,
        },
        {
          title: "审批人",
          key: "spr",
          type: "choose",
          selectList: audit,
          selectKey: "ACCOUNT",
          value: this.xfsprArr.length ? this.xfsprArr : [0],
          disabled,
        },
        {
          title: "用车事由",
          key: "ycsy",
          type: "textarea",
          maxLength: 300,
          value: order ? order.ycsy : "",
          disabled,
        },
        {
          title: "用车人数",
          key: "ycrs",
          type: "number",
          ruleList: ["isNum", "numMin:1"],
          ruleMsgList: ["用车人数必须是纯数字无小数", "用车人数最小为1"],
          skip: true,
          value: order ? order.ycrs : "",
          disabled,
          hidden: order ? !order.ycrs : false,
        },
        {
          title: "开始地点",
          key: "ksdd",
          skip: true,
          maxLength: 200,
          value: order ? order.ksdd : "",
          disabled,
          hidden: order ? !order.ksdd : false,
        },
        {
          title: "结束地点",
          key: "jsdd",
          maxLength: 200,
          skip: true,
          value: order ? order.jsdd : "",
          disabled,
          hidden: order ? !order.jsdd : false,
        },
        {
          title: "停车地点",
          key: "tcdd",
          maxLength: 200,
          skip: true,
          value: order ? order.tcdd : "",
          disabled,
          hidden: order ? !order.tcdd : false,
        },
        {
          title: "附件",
          key: "file",
          type: "img",
          skip: true,
          imgCount: 8,
          value: order ? order.file : [],
          disabled,
          hidden: order ? !order.file.length : false,
        },
        {
          title: "备注",
          key: "bz",
          type: "textarea",
          maxLength: 200,
          skip: true,
          value: order ? order.bz : "",
          disabled,
          hidden: order ? !order.bz : false,
        },
      ];
      if (this.order && this.order.spgcList && this.order.spgcList.length) {
        rules.push({
          title: `<div class="custom-tip">流程历史</div>`,
          type: "custom",
          key: "recognition",
        });
        this.order.spgcList.forEach((item, index) => {
          rules.push({
            title: `<div class="custom-sp">${item.spjg}&#12288;${
              item.spr_desc
            }&#12288;${item.spsj.substring(0, 16)}</div>`,
            type: "custom",
            key: "sp" + index,
          });
        });
      }
      this.$nextTick(() => {
        this.$refs.basicsForm.initForm(rules);
      });
    },
    //提交
    submit(param) {
      if (!param) {
        return;
      }
      param.pzhAuthorization = this.pzhAuthorization;
      param.cph_id = this.car[param.cph].id;
      param.cph = this.car[param.cph].clgl_cph;
      let xfsprList = [];
      param.spr.forEach((item, index) => {
        xfsprList.push({
          spr: item,
          sort: index + 1,
          status: 0,
        });
        param["spr" + (index + 1)] = item;
      });
      param.xfsprList = JSON.stringify(xfsprList);
      delete param.spr;
      if (param.file && param.file.length) {
        let files = [];
        param.file.map((value, index) => {
          if (value.indexOf("://125.66.234.97") < 0) {
            files.push(value);
          }
        });
        let imgs = files.map((value, index) => {
          return {
            name: "file" + index,
            uri: value,
          };
        });
        param.fileNum = param.file.length;
        delete param.file;
        uni.uploadFile({
          url: this.$util.getApiUrl() + "panzhihua/jsp/zhgl/insertClglPcgl.do",
          files: imgs,
          formData: param,
          success: (res) => {
            if (
              res.statusCode == 200 &&
              JSON.parse(res.data).resCode == "success"
            ) {
              uni.hideLoading();
              uni.showToast({
                icon: "success",
                title: "操作成功",
                duration: 2000,
              });
              setTimeout(() => {
                this.$util.backToRefreshPrevPage("carOrder");
              }, 1500);
            }
          },
        });
      } else {
        this.$api.insertClglPcgl(param).then((res) => {
          if (res.resCode == "success") {
            uni.hideLoading();
            uni.showToast({
              icon: "success",
              title: "操作成功",
              duration: 2000,
            });
            setTimeout(() => {
              setTimeout(() => {
                this.$util.backToRefreshPrevPage("carOrder");
              }, 1500);
            }, 2000);
          }
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .custom-tip {
  color: $theme-color;
  line-height: 120rpx;
}
::v-deep .custom-sp {
  line-height: 120rpx;
}
</style>